package com.programmercarl.array;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/remove-element/description/
 *
 * @author yulongtian
 * @create 2024-12-10 13:33
 */
public class Test06 {
    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
        int val = 2;
        int[] expectedNums = {0, 1, 4, 0, 3}; // 长度正确的预期答案。
        System.out.println(removeElement(nums, val));
        System.out.println(Arrays.toString(nums));
    }

    public static int removeElement(int[] nums, int val) {
        Arrays.sort(nums);
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                continue;
            }
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] != val) {
                    swap(nums, i, j);
                }
            }
        }
        for (int i = nums.length - 1; i >= 0; i--) {
            if (nums[i] != val) {
                break;
            }
            k++;
        }


        return nums.length - k;
    }

    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

}
